﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Windows;
using Microsoft.Data.Sqlite;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Options;
using Protocal.App.Common;
using 多协议通信平台.DAL;
using 多协议通信平台.IService;
using 多协议通信平台.Service;

namespace 多协议通信平台.Common
{
    public class IocHelper
    {
        private static Dictionary<string, FrameworkElement> Container = new Dictionary<string, FrameworkElement>();
        private static Type[] Types;

        public static FrameworkElement GetInstance(string url)
        {
            if (string.IsNullOrEmpty(url))
                throw new ArgumentNullException("提供的 url 不能为空");
            if (Container.ContainsKey(url))
                return Container[url];

            if (Types == null || Types.Length == 0)
            {
                Types = Assembly.GetExecutingAssembly().GetTypes();
            }
            Type type = Types.FirstOrDefault(f => f.FullName.Equals(url));
            if (type == null)
                throw new Exception("菜单地址不存在");
            Container[url] = (FrameworkElement)Activator.CreateInstance(type);
            return Container[url];
        }

        public static IBaseService GetService()
        {
            string? sqliteDbConn = AppSetting.Get<string>("SqliteDb");
            DbContextOptionsBuilder builder = new DbContextOptionsBuilder();
            builder.UseSqlite(sqliteDbConn);
#if DEBUG
            //启用敏感数据日志记录
            builder.EnableSensitiveDataLogging();

            //记录日志          
            builder.LogTo(msg =>
            {
                //调试-窗口消息
                System.Diagnostics.Debug.WriteLine(msg);

                //输出-窗口消息
                Console.WriteLine(msg);

            }, Microsoft.Extensions.Logging.LogLevel.Information);
#endif
            AppDbContext appDbContext = new AppDbContext(builder.Options);
            return new BaseService(appDbContext);
        }
    }
}
